# coding=utf-8
# 导入python包
import numpy as np
import imutils
import cv2

def is_contour_bad(c):
	# 近似轮廓
	peri = cv2.arcLength(c, True)
	approx = cv2.approxPolyDP(c, 0.02 * peri, True)

	# 判断当前的轮廓是不是矩形
	return not len(approx) == 4

# 首先读取图片；然后进行颜色转换；最后进行边缘检测
image = cv2.imread("remove.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(gray, 50, 100)
cv2.imshow("Original", image)

# 寻找图中的轮廓并设置mask
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
mask = np.ones(image.shape[:2], dtype="uint8") * 255

# 循环遍历所有的轮廓
for c in cnts:
	# 检测该轮廓的类型，在新的mask中绘制结果
	if is_contour_bad(c):
		cv2.drawContours(mask, [c], -1, 0, -1)

# 移除不满足条件的轮廓并显示结果
image = cv2.bitwise_and(image, image, mask=mask)
cv2.imwrite("Mask.png", mask)
cv2.imshow("Mask", mask)
cv2.imwrite("result.png", image)
cv2.imshow("After", image)
cv2.waitKey(0)